<template>
    <div class="background">
        <div class="more-clan-famous">
            <!-- 第一部分：搜索和筛选（居中显示） -->
            <section class="filter-section">
                <div class="filter-container">
                    <el-input v-model="searchQuery" placeholder="搜索名人..." class="search-input" :prefix-icon="Search"
                        clearable />

                    <el-select v-model="famousType" class="type-select" placeholder="选择名人类型">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
            </section>

            <!-- 第二部分：名人卡片网格 -->
            <section class="grid-section">
                <div class="person-grid">
                    <div v-for="(person, index) in displayedPersons" :key="person.id" @click="openDialog(person)"
                        class="person-card" @mouseenter="hoverIndex = index" @mouseleave="hoverIndex = -1">
                        <div class="cover" :style="{
                            backgroundImage: person.cover ? `url(${person.cover})` : 'none',
                            transform: hoverIndex === index ? 'scale(1.05)' : 'scale(1)'
                        }">
                            <div class="cover-placeholder" v-if="!person.cover">
                                {{ person.name.charAt(0) }}
                            </div>
                        </div>
                        <div class="info">
                            <div class="name">{{ person.name }}</div>
                            <div class="meta">
                                <span class="type">{{ person.type === 'clan' ? '家族名人' : '公开名人' }}</span>
                                <span class="likes">
                                    <el-icon>
                                        <Star />
                                    </el-icon>
                                    {{ person.likes }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 加载更多按钮 -->
                <div class="load-more-container" v-if="!noMore">
                    <el-button class="load-more-btn" :loading="loading" @click="loadMore">
                        {{ loading ? '加载中...' : '加载更多' }}
                    </el-button>
                </div>
                <div v-if="noMore" class="no-more-text">已加载全部数据</div>
            </section>

            <FamousDetail v-if="showDialog" :person="selectedPerson" @close="showDialog = false"
                @comment-submitted="handleCommentSubmit" @comment-deleted="handleCommentDelete" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Star } from '@element-plus/icons-vue'
import FamousDetail from './FamousDetail.vue'

const showDialog = ref(false);
const selectedPerson = ref({
    id: 1,
    name: '张氏先祖',
    bio: '张氏家族创始人，生于明朝万历年间...',
    // 其他数据...
})

const openDialog = (person: any) => { 
    selectedPerson.value = person;
    showDialog.value = true;
};

const handleCommentSubmit = (comment: any) => {
    console.log('新评论:', comment)
}

const handleCommentDelete = (comment: any) => {
    console.log('删除评论:', comment)
}

// 搜索和筛选相关
const searchQuery = ref('')
const famousType = ref('clan') // 默认显示家族名人
const options = [
    { value: 'all', label: '全部名人' },
    { value: 'clan', label: '家族名人' },
    { value: 'public', label: '公开名人' }
]
const hoverIndex = ref(-1)

// 分页相关
const pageSize = 9
const currentPage = ref(1)
const loading = ref(false)
const noMore = ref(false)

// 生成模拟数据函数
const generateMockData = (count: number) => {
    const types = ['clan', 'public']
    const surnames = ['张', '李', '王', '赵', '刘', '陈', '杨', '黄', '周', '吴']
    const names = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军']
    const titles = ['先祖', '宗长', '贤达', '名士', '先贤', '长老', '先生', '夫人']

    return Array.from({ length: count }, (_, i) => ({
        id: i + 1,
        name: `${surnames[i % surnames.length]}${names[i % names.length]}${titles[i % titles.length]}`,
        type: types[i % 2], // 交替分配类型
        likes: Math.floor(Math.random() * 1000),
        cover: '' // 实际项目中替换为真实图片URL
    }))
}

// 所有数据
const allPersons = ref(generateMockData(100))

// 当前显示的数据
const displayedPersons = computed(() => {
    let filtered = allPersons.value

    // 按类型筛选
    if (famousType.value !== 'all') {
        filtered = filtered.filter(person => person.type === famousType.value)
    }

    // 按搜索词筛选
    if (searchQuery.value) {
        filtered = filtered.filter(person =>
            person.name.includes(searchQuery.value)
        )
    }

    // 分页切片
    return filtered.slice(0, currentPage.value * pageSize)
})

// 加载更多数据
const loadMore = () => {
    loading.value = true
    setTimeout(() => {
        currentPage.value++
        loading.value = false

        // 检查是否还有更多数据
        const totalFiltered = allPersons.value.filter(person => {
            const typeMatch = famousType.value === 'all' || person.type === famousType.value
            const searchMatch = !searchQuery.value || person.name.includes(searchQuery.value)
            return typeMatch && searchMatch
        }).length

        noMore.value = displayedPersons.value.length >= totalFiltered
    }, 800) // 模拟网络延迟
}

// 当搜索或筛选条件变化时重置分页
watch([searchQuery, famousType], () => {
    currentPage.value = 1
    noMore.value = false
})

// 初始化加载第一页
onMounted(() => {
    // 初始检查是否还有更多数据
    const totalFiltered = allPersons.value.filter(person => {
        const typeMatch = famousType.value === 'all' || person.type === famousType.value
        const searchMatch = !searchQuery.value || person.name.includes(searchQuery.value)
        return typeMatch && searchMatch
    }).length

    noMore.value = displayedPersons.value.length >= totalFiltered
})
</script>

<style scoped lang="scss">
.background {
    background-color: #f5efe6;
    min-height: 100vh;
    padding: 20px 0;
}

.more-clan-famous {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* 筛选部分样式 - 居中 */
.filter-section {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;

    .filter-container {
        display: flex;
        gap: 20px;
        align-items: center;
        justify-content: center;
        width: 100%;
        flex-wrap: wrap;

        .search-input {
            flex: 1;
            max-width: 400px;
            min-width: 250px;
        }

        .type-select {
            width: 200px;
            min-width: 150px;
        }
    }
}

/* 网格部分样式 */
.grid-section {
    flex: 1;
    padding-bottom: 20px;
    display: flex;
    flex-direction: column;

    .person-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20px;
        margin-bottom: 20px;

        .person-card {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            cursor: pointer;

            &:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                transform: translateY(-5px);
            }

            .cover {
                height: 200px;
                background-size: cover;
                background-position: center;
                transition: transform 0.3s ease;
                background-color: var(--el-color-primary-light-8);
                position: relative;

                .cover-placeholder {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: var(--el-color-primary-light-8);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: var(--el-color-primary);
                    font-size: 48px;
                    font-weight: bold;
                }
            }

            .info {
                padding: 15px;

                .name {
                    color: var(--el-color-primary);
                    font-size: 18px;
                    font-weight: bold;
                    margin-bottom: 10px;
                }

                .meta {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .type {
                        font-size: 14px;
                        color: var(--el-text-color-secondary);
                        background-color: var(--el-color-primary-light-8);
                        padding: 2px 8px;
                        border-radius: 4px;
                    }

                    .likes {
                        color: var(--el-color-warning);
                        font-size: 14px;
                        display: flex;
                        align-items: center;

                        .el-icon {
                            margin-right: 4px;
                        }
                    }
                }
            }
        }
    }

    .load-more-container {
        display: flex;
        justify-content: center;
        margin: 20px 0;

        .load-more-btn {
            padding: 12px 36px;
            font-size: 16px;
        }
    }

    .no-more-text {
        text-align: center;
        padding: 20px;
        color: var(--el-text-color-secondary);
    }
}

/* 响应式调整 */
@media (max-width: 992px) {
    .grid-section .person-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .filter-section .filter-container {
        flex-direction: column;
        align-items: stretch;

        .search-input,
        .type-select {
            width: 100%;
            max-width: 100%;
        }
    }
}

@media (max-width: 576px) {
    .grid-section .person-grid {
        grid-template-columns: 1fr;
    }

    .more-clan-famous {
        padding: 15px;
    }
}
</style>